<?php 
namespace app\common\library;
use fast\Http;
class Ai{
    // 接口令牌
    protected $key = "app-ToZ3j1au2yrXqFRvR89wsFgw";
    // 接口請求路徑
    protected $url = "https://dify.fitcamp.net.cn/v1";
    /**
     * 单例对象
     */
    protected static $instance;
    /**
     * 配置對象
     */
    protected $options = [];

    /**
     * 初始化
     * @access public
     * @param array $options 参数
     * @return Email
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }

        return self::$instance;
    }
    /**
     * 构造函数
     * @param array $options
     */
    public function __construct($options = [])
    {
        $this->options = array_merge($this->options, $options);
    }
    /**
     * 爬蟲email
     */
    public function getEmails($url,$depth=2){
        $params = ['response_mode' => 'blocking','user' => 'aiedm','inputs' => ['url' => $url,'depth' => $depth]];
        $response = $this->_post("/workflows/run",$params);
        $emails = [];
        if(isset($response['data']['outputs']) && !empty($response['data']['outputs']) && is_array($response['data']['outputs'])){
            foreach($response['data']['outputs'] as $email){
                $answers = json_decode($email,true);
                $answers = isset($answers['answer']) ? $answers['answer'] : $answers;
                if(!empty($answers) && is_array($answers)){
                    foreach($answers as $email){
                        $emails[] = $email;
                    }
                }
            }
        }
        return $emails;
    }
    /**
     * http 請求數據
     */
    protected function _post($path,$params=[]){
         $options[CURLOPT_HTTPHEADER] = [
            'Authorization: Bearer '.$this->key,
            'Content-Type:application/json'
        ];
        $response = Http::post($this->url.$path,json_encode($params,JSON_UNESCAPED_UNICODE),$options);
        return json_decode($response,true);
    }
}